const bcrypt = require('bcryptjs');
const jwt = require('jwt-simple');
const secretKey = "hnzjjszc";


module.exports = {
    //服务人员权限审核中间件
    serverAuthenticated: function serverAuthenticated(req, res, next) {
        if (!req.header('Authorization')) {
            return res.status(401).send({ message: '无请求头' });
        }
        const token = req.header('Authorization').split(' ')[1];
        let payload;
        try {
            payload = jwt.decode(token, secretKey);
        }
        catch (err) {
            return res.status(401).send({ message: err.message });
        }

        // //验证token时效
        // if (!payload.exp || payload.exp <= Date.now()) {
        //     return res.status(401).send({ message: '登录过期' });
        // }

        if (!payload.userName) {
            return res.status(401).send({ message: '无权限' });
        } else {
            req.user = payload;
            next();
        }
    },
    //管理员权限审核中间件
    adminAuthenticated: function adminAuthenticated(req, res, next) {
        console.log(req.header('Authorization'));
        if (!req.header('Authorization')) {
            return res.status(401).send({ message: '无请求头' });
        };
        next();
        
    },
    //用户权限审核中间件
    userAuthenticated: function userAuthenticated(req, res, next) {
        if (!req.header('Authorization')) {
            return res.status(401).send({ message: '无请求头' });
        }
        const token = req.header('Authorization').split(' ')[1];
        let payload;
        try {
            payload = jwt.decode(token, secretKey);
        }
        catch (err) {
            return res.status(401).send({ message: err.message });
        }
        // //验证token时效
        // if (!payload.exp || payload.exp <= Date.now()) {
        //     return res.status(401).send({ message: '登录过期' });
        // }
        req.user = {};
        if (!payload.userid) {
            return res.status(401).send({ message: '无权限' });
        } else {
            req.user = payload;
            next();
        }
    },
    //生成jwt token
    createJWT: function createJWT(user) {
        const payload = user;
        payload.exp = Date.now() + 30 * 60 * 1000;
        try {
            return jwt.encode(payload, secretKey);
        } catch (error) {
            throw new Error(error);
        }
    }
};